package com.gsxi.tyagbackend.utils.exception;

import com.gsxi.tyagbackend.utils.enums.ResponseCodeEnum;
import com.gsxi.tyagbackend.utils.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: gsxi
 * @CreateTime: 2024-07-17
 * @Description: 全局异常处理
 * @Version: 1.0
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获自定义业务异常
     * @return AjaxResult
     */
    @ExceptionHandler({ BizException.class })
    @ResponseBody
    public AjaxResult handleBizException(HttpServletRequest request, BizException e) {
        log.warn("{} request fail, errorCode: {}, errorMessage: {}", request.getRequestURI(), e.getErrorCode(), e.getErrorMessage());
        return AjaxResult.error(e);
    }

    /**
     * 捕获其他异常
     * @param request 请求
     * @param e 异常
     * @return AjaxResult
     */
    @ExceptionHandler({ Exception.class })
    @ResponseBody
    public AjaxResult handleOtherException(HttpServletRequest request, Exception e) {
        log.error("{} request error, ", request.getRequestURI(), e);
        return AjaxResult.error(ResponseCodeEnum.UNKNOWN_ERROR);
    }
}
